package com.csx.tree;

/**
 * @author 陈胤训
 * @date 2019/6/3 11:07
 * Utils: Intellij Idea
 * Description: 线段树
 */
public class SegmentTree<E> {

    private E[] data;

    private E[] tree;

    private  Merger<E> merger;

    public SegmentTree(E[] data, Merger<E> merger) {
        this.merger = merger;
//        this.data = data;
        this.data = (E[]) new Object[data.length];
        for (int i = 0; i < data.length; i++) {
            this.data[i] = data[i];
        }

        this.tree = (E[])new Object[4 * data.length];

        buildSegmentTree(0,0,data.length - 1);
    }

    /**
     * 在 treeIndex 的位置创建表示区间{l....r}的线段树
     * @param treeIndex 线段树索引
     * @param l 开始
     * @param r 结束
     */
    private void buildSegmentTree(int treeIndex, int l, int r) {
        if ( l == r){
            tree[treeIndex] = data[l];
            return;
        }
        int leftTreeIndex = leftChild(treeIndex);
        int rightTreeIndex = rightChild(treeIndex);

        // 区间范围
        // int mid = (l + r) / 2;
        int mid = l + (r - l) / 2;

        // l    -   mid 区间
        buildSegmentTree(leftTreeIndex, l, mid);
        // mid+1   -   r 区间
        buildSegmentTree(rightTreeIndex, mid + 1, r);

        tree[treeIndex] = merger.merge(tree[leftTreeIndex], tree[rightTreeIndex]);
    }

    public E get(int index){
        if (index < 0 || index >= data.length){
            throw new IllegalArgumentException("Index is illegal");
        }
        return data[index];
    }

    public int getSize(){
        return data.length;
    }

    /**
     *  返回完全二叉树的数组表示中, 一个索引表示的元素左孩子节点的索引
     * @param index 索引
     * @return 左孩子索引
     */
    private int leftChild(int index){
        return 2 * index + 1;
    }

    /**
     *  返回完全二叉树的数组表示中, 一个索引表示的元素右孩子节点的索引
     * @param index 索引
     * @return 右孩子索引
     */
    private int rightChild(int index){
        return 2 * index + 2;
    }

    /**
     * 返回区间[queryL, queryR]的值
     * @param queryL 搜索开始
     * @param queryR 搜索结束
     * @return 值
     */
    public E query(int queryL, int queryR){

        if(queryL < 0 || queryL >= data.length ||
                queryR < 0 || queryR >= data.length || queryL > queryR){
            throw new IllegalArgumentException("Index is illegal.");
        }

        return query(0, 0, data.length - 1, queryL, queryR);
    }

    /**
     * 在以treeIndex为根的线段树中[l...r]的范围里，搜索区间[queryL...queryR]的值
     * @param treeIndex  线段树索引
     * @param l 开始
     * @param r 结束
     * @param queryL 搜索开始
     * @param queryR 搜索结束
     * @return 值
     */
    private E query(int treeIndex, int l, int r, int queryL, int queryR){

        if(l == queryL && r == queryR){
            return tree[treeIndex];
        }

        int mid = l + (r - l) / 2;
        // treeIndex的节点分为[l...mid]和[mid+1...r]两部分

        int leftTreeIndex = leftChild(treeIndex);
        int rightTreeIndex = rightChild(treeIndex);
        if(queryL >= mid + 1){
            return query(rightTreeIndex, mid + 1, r, queryL, queryR);
        }
        else if(queryR <= mid){
            return query(leftTreeIndex, l, mid, queryL, queryR);
        }

        E leftResult = query(leftTreeIndex, l, mid, queryL, mid);
        E rightResult = query(rightTreeIndex, mid + 1, r, mid + 1, queryR);
        return merger.merge(leftResult, rightResult);
    }

    /**
     * 将index位置的值,更新为e
     * @param index
     * @param e
     */
    public void set(int index, E e){
        if(index < 0 || index >= data.length){
            throw new IllegalArgumentException("Index is illegal");
        }
        data[index] = e;
        set(0, 0, data.length - 1, index, e);
    }

    /**
     * 在以reeIndex 为根的线段树中更新index的值为e
     * @param treeIndex
     * @param l
     * @param r
     * @param index
     * @param e
     */
    private void set(int treeIndex, int l, int r, int index, E e) {
        if ( l == r){
            tree[treeIndex] = e;
            return;
        }
        int leftTreeIndex = leftChild(treeIndex);
        int rightTreeIndex = rightChild(treeIndex);

        // 区间范围
        // int mid = (l + r) / 2;
        int mid = l + (r - l) / 2;
        if (index >= mid +1){
            set(rightTreeIndex, mid + 1, r, index, e);
        }else{
            set(leftTreeIndex, l, mid, index, e);
        }

        tree[treeIndex] = merger.merge(tree[leftTreeIndex], tree[rightTreeIndex]);
    }

    @Override
    public String toString(){
        StringBuilder res = new StringBuilder();
        res.append('[');
        for(int i = 0 ; i < tree.length ; i ++){
            if(tree[i] != null){
                res.append(tree[i]);
            }else{
                res.append("null");
            }
            if(i != tree.length - 1){
                res.append(", ");
            }

        }
        res.append(']');
        return res.toString();
    }

    public static void main(String[] args) {
        Integer[] nums = {99,88,0, 1, 2, 3, 4};
        SegmentTree<Integer> segmentTree = new SegmentTree<>(nums, new Merger<Integer>() {
            @Override
            public Integer merge(Integer a, Integer b) {
                return a + b;
            }
        });
        SegmentTree<Integer> segmentTree1 = new SegmentTree<>(nums, (a,b) -> a+b);
        System.out.println(segmentTree);
        Integer query = segmentTree.query(0, 4);
        System.out.println(query);

    }
}
